﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using SqlServerWrapper;

namespace ZCrawler
{
    public class ZPublisherManager
    {
        public static void Process(ZResultSet results,
                                   ZPublisher publisher,
                                   Action<Exception> onErrorHandler,
                                   Action onCompletionHandler,
                                   Action<ZResult> onStepHandler)
        {
            if (!publisher.isActivated) return;
            Type p_type = publisher.GetType();
            if(p_type.IsEquivalentTo(typeof(ZSQLPublisher)))
            {
                SQLImport(results,(ZSQLPublisher)publisher,onErrorHandler,onCompletionHandler,onStepHandler);
            }
            else if(p_type.IsEquivalentTo(typeof(ZDocumentPublisher)))
            {

            }
        }

        private static void SQLImport(ZResultSet results,
                                      ZSQLPublisher publisher,
                                      Action<Exception> onErrorHandler,
                                      Action onCompletionHandler,
                                      Action<ZResult> onStepHandler)
        {
            try
            {
                using (SqlConnection conn = publisher.MakeConnection())
                {
                    conn.Open();
                    using (SqlTransaction trans = conn.BeginTransaction())
                    {
                        using (SqlCommand cmd = SqlCommandManager.Create(conn, publisher.sql_command_type))
                        {
                            cmd.CommandText = publisher.sql_command_text;
                            cmd.Transaction = trans;
                            foreach (ZResult result in results)
                            {
                                //foreach (string key in result.DATA.Keys)
                                //{
                                //    cmd.Parameters.Add("@" + publisher.mapper.GetOriKeyFromMappedKey(key), SqlDbType.VarChar).Value = key.;
                                //}
                                publisher.mapper.OriginalKeys.ForEach(k =>
                                    {
                                        if(!publisher.mapper.GetMappedKeyFromOriKey(k).StartsWith("#text#"))
                                            cmd.Parameters.Add(k, SqlDbType.VarChar).Value = result.DATA.ContainsKey(publisher.mapper.GetMappedKeyFromOriKey(k)) ? result.DATA[publisher.mapper.GetMappedKeyFromOriKey(k)].ToString() : DBNull.Value.ToString();
                                        else
                                            cmd.Parameters.Add(k, SqlDbType.VarChar).Value = publisher.mapper.GetMappedKeyFromOriKey(k).Replace("#text#","");
                                    });
                                cmd.ExecuteNonQuery();
                                if (onStepHandler != null) onStepHandler(result);
                                cmd.Parameters.Clear();
                            }

                            try
                            {
                                trans.Commit();
                            }
                            catch (Exception ex)
                            {
                                trans.Rollback();
                                if (onErrorHandler != null)
                                    onErrorHandler(ex);
                            }
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                if (onErrorHandler != null)
                    onErrorHandler(ex);
            }
        }
    }
}
